// 状态管理
const state = {
  pageNum: 1,
  pageSize: 10,
  total: 0,
  tableData: []
}

// 视图渲染
const viewRender = {
  renderSelect(selectIds, name, api, defaultText = "所有选项") {
    selectIds.forEach((selectId) => {
      api().then((response) => {
        if (response.code === 200) {
          let list = response.data;

          $("<option></option>")
            .attr("name", name)
            .attr("value", "")
            .text(defaultText)
            .prop("hidden", true)
            .prop("selected", false)
            .appendTo(selectId);

          $.each(list, function (index, item) {
            $("<option></option>")
              .attr("name", name)
              .attr("value", item.id)
              .text(item.name)
              .appendTo(selectId);
          });
        }
      });
    });

  },
  renderSelects() {
    this.renderSelect(["#search-form-role", "#modal-form-role"], "roleId", listRole, "所有角色");
    this.renderSelect(["#search-form-position", "#modal-form-position"], "positionId", listPosition, "所有位置");
    this.renderSelect(["#search-form-team", "#modal-form-team"], "teamId", listTeam, "所有球队");
  },
  renderTableAndPagination() {
    this.renderTable()
    this.renderPagination()
  },
  loadTableData() {
    this.showLoading(true);
    const body = {
      username: $("#search-from-username").val() || null,
      firstname: $("#search-from-firstname").val() || null,
      lastname: $("#search-from-lastname").val() || null,
      roleId: $("#search-form-role").val() || null,
      positionId: $("#search-form-position").val() || null,
    };

    listUser(body, {
      pageNum: state.pageNum,
      pageSize: state.pageSize
    }).then((response) => {
      state.tableData = response.data.records;
      state.total = response.data.total;
      this.renderTableAndPagination()
    })
      .catch((error) => {
        console.error(error);
      })
      .finally(() => {
        this.showLoading(false);
      });
  },

  renderTable() {
    const $tbody = $("#tbody");
    $tbody.empty();

    if (state.tableData.length === 0) {
      $tbody.append(`
                <tr>
                    <td colspan="7" class="text-center py-4 text-muted">No matching data found!</td>
                </tr>
            `);
      return;
    }

    state.tableData.forEach((user) => {
      $tbody.append(`
                <tr>
                    <td>${user.id}</td>
                    <td>
                        <div class="d-flex align-items-center">
                           ${user.username}
                        </div>
                    </td>
                    <td>${user.firstname || ""} ${user.lastname || ""}</td>
                    <td>${user.age || ""}</td>
                    <td><span class="badge bg-warning text-dark">${
        user.role ? user.role.name : ""
      }</span></td>
                    <td><span class="badge bg-warning text-dark">${
        user.team ? user.team.name : ""
      }</span></td>
                    <td><span class="badge bg-info text-dark">${
        user.position ? user.position.name : ""
      }</span></td>
                    <td>
                        <button class="btn btn-sm btn-primary edit-btn" data-id="${
        user.id
      }">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger delete-btn" data-id="${
        user.id
      }">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `);
    });
  },
  renderPagination() {
    const $pagination = $("#pagination");
    $pagination.empty();

    // 上一页按钮
    $pagination.append(`
            <li class="page-item ${state.pageNum === 1 ? "disabled" : ""}">
                <a class="page-link" href="#" data-page="${state.pageNum - 1}">
                    <i class="fas fa-angle-left"></i>
                </a>
            </li>
        `);

    // 页码按钮
    const startPage = Math.max(1, state.pageNum - 2);
    const endPage = Math.min(Math.ceil(state.total / state.pageSize), state.pageNum + 2);

    for (let i = startPage; i <= endPage; i++) {
      $pagination.append(`
                <li class="page-item ${i === state.pageNum ? "active" : ""}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
    }

    // 下一页按钮
    $pagination.append(`
            <li class="page-item ${
      state.pageNum === Math.ceil(state.total / state.pageSize) ? "disabled" : ""
    }">
                <a class="page-link" href="#" data-page="${state.pageNum + 1}">
                    <i class="fas fa-angle-right"></i>
                </a>
            </li>
        `);
  },
  showLoading(show) {
    $("#loading-spinner").toggle(show);
    $(".table-responsive").toggle(!show);
  }
}

// 事件处理
const eventHandler = {
  bindEventListeners() {
    // 搜索按钮点击事件
    $("#search-btn").on("click", function () {
      viewRender.loadTableData();
    });

    // 重置搜索条件
    $("#reset-btn").on("click", function () {
      $("#search-from-username").val("");
      $("#search-from-firstname").val("");
      $("#search-from-lastname").val("");
      $("#search-form-role").val("");
      $("#search-form-position").val("");
      viewRender.loadTableData();
    });

    // 分页点击事件
    $("#pagination").on("click", ".page-link", function (e) {
      e.preventDefault();
      const page = $(this).data("page");
      if (page >= 1 && page <= Math.ceil(state.total / state.pageSize)) {
        state.pageNum = page;
        viewRender.loadTableData();
      }
    });

    // 添加用户按钮点击事件
    $("#add-btn").on("click", function () {
      $("#modal-form")[0].reset();
      $("#modal-form-id").val("");
      $("#modal-title").text("添加用户");
      $("#modal").modal("show");
    });

    // 编辑按钮点击事件（委托事件处理）
    const $tbody = $("#tbody");
    $tbody.on("click", ".edit-btn", function () {
      const userId = $(this).data("id");
      const $btn = $(this);

      $btn.html('<span class="spinner-border spinner-border-sm"></span>');
      $btn.prop("disabled", true);

      http
        .get(`/user/get?id=${userId}`)
        .then((response) => {
          const user = response.data;
          $("#modal-form-id").val(user.id);
          $("#modal-form-username").val(user.username);
          $("#modal-form-role").val(user.roleId);
          $("#modal-form-team").val(user.teamId);
          $("#modal-form-firstname").val(user.firstname);
          $("#modal-form-lastname").val(user.lastname);
          $("#modal-form-age").val(user.age);
          $("#modal-form-position").val(user.positionId);

          $("#modal-title").text("编辑用户");
          $("#modal").modal("show");

          $("").children();
        })
        .catch((error) => {
          console.error("获取用户信息失败:", error);
          alert("获取用户信息失败");
        })
        .finally(() => {
          $btn.html('<i class="fas fa-edit"></i>');
          $btn.prop("disabled", false);
        });
    });

    // 删除按钮点击事件（委托事件处理）
    $tbody.on("click", ".delete-btn", function () {
      const userId = $(this).data("id");
      const $btn = $(this);

      if (confirm("确定要删除这个用户吗？")) {
        $btn.html('<span class="spinner-border spinner-border-sm"></span>');
        $btn.prop("disabled", true);

        deleteUser(userId)
          .then((response) => {
            if (response.code === 200) {
              alert("删除成功");
              viewRender.loadTableData();
            } else {
              alert("删除失败: " + (response.message || "未知错误"));
            }
          })
          .catch((error) => {
            console.error("删除用户失败:", error);
            alert("删除用户失败");
          })
          .finally(() => {
            $btn.html('<i class="fas fa-trash"></i>');
            $btn.prop("disabled", false);
          });
      }
    });

    // 保存用户表单
    $("#save-btn").on("click", function () {
      const $form = $("#modal-form");
      const userId = $("#modal-form-id").val();

      if (!$form[0].checkValidity()) {
        $form[0].reportValidity();
        return;
      }

      const userData = {
        id: userId || null,
        username: $("#modal-form-username").val(),
        roleId: $("#modal-form-role").val() || null,
        teamId: $("#modal-form-team").val() || null,
        positionId: $("#modal-form-position").val() || null,
        firstname: $("#modal-form-firstname").val(),
        lastname: $("#modal-form-lastname").val(),
        age: $("#modal-form-age").val() || null,
        password: $("#modal-form-password").val() || undefined,
      };

      const $btn = $(this);
      $btn.html(
        '<span class="spinner-border spinner-border-sm"></span> 保存中...'
      );
      $btn.prop("disabled", true);

      const request = userId ? updateUser(userData) : addUser(userData);

      request
        .then((response) => {
          if (response.code === 200) {
            alert(userId ? "用户信息已更新" : "用户添加成功");
            $("#modal").modal("hide");
            viewRender.loadTableData();
          } else {
            alert(
              (userId ? "更新" : "添加") +
              "用户失败: " +
              (response.message || "未知错误")
            );
          }
        })
        .catch((error) => {
          console.error("保存用户失败:", error);
          alert("保存用户失败");
        })
        .finally(() => {
          $btn.html("保存");
          $btn.prop("disabled", false);
        });
    });
  }

}

// 初始化
$(document).ready(function () {
  viewRender.renderSelects()
  viewRender.loadTableData()
  eventHandler.bindEventListeners()
});
